<?php
/**
 * Created by PhpStorm.
 * User: 丶晓
 * Date: 2017/8/25
 * Time: 9:25
 */

namespace app\common\Qiniu;


use Qiniu\Auth;
use app\common\Base;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;

class PlaySDK extends Base
{
    private $appid;
    private $appsecret;

    public function __construct($appid, $appsecret)
    {
        $this->appid = $appid;
        $this->appsecret = $appsecret;
    }

    /*
     * 上传文件 $_FILE = $file
     *
     */
    public function upFile_put($file, $key, $bucket)
    {
        $token = $this->getUpdataToken($bucket);
        // 初始化 UploadManager 对象并进行文件的上传
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($ret, $err) = $uploadMgr->put($token, $key, $file);
        if ($err !== null) {
            return $err;
        } else {
            return $ret;
        }
    }

    /*
     * 私有文件下载
     */
    public function downloadFile_vip($key, $is_ssl = true)
    {
        $url = ($is_ssl ? 'https://' : 'http://') . 'vip.res.suyongw.com/' . $key;
        // 需要填写你的 Access Key 和 Secret Key
        $accessKey = $this->appid;
        $secretKey = $this->appsecret;
        // 构建鉴权对象
        $auth = new Auth($accessKey, $secretKey);
        return $auth->privateDownloadUrl($url);
    }

    /*
     * 换取下载链接
     * 根据 $key
     *  ssl 可选
     */
    public function downloadFile_url($key, $is_ssl = false)
    {
        return ($is_ssl ? 'https://' : 'http://') . 'res.suyongw.com/' . $key;
    }

    public function downloadFile_urls($key, $is_ssl = false)
    { 
         foreach ($key as $key => $value) {
             $res[] =($is_ssl ? 'https://' : 'http://') . 'res.suyongw.com/' . $value;
         }
        return $res;
    }

    /*
     * 删除文件 指定 资源名称 与 资源空间
     */
    public function delFileByKey($bucket, $key)
    {
        // 需要填写你的 Access Key 和 Secret Key
        $accessKey = $this->appid;
        $secretKey = $this->appsecret;
        // 构建鉴权对象
        $auth = new Auth($accessKey, $secretKey);
        $bucketMgr = new BucketManager($auth);
        $err = $bucketMgr->delete($bucket, $key);
        if ($err !== null) {
            return false;
        }
        return true;
    }

    /*
     * 获取上传文件Token
     */
    public function getUpdataToken($bucket)
    {
        // 需要填写你的 Access Key 和 Secret Key
        $accessKey = $this->appid;
        $secretKey = $this->appsecret;
        // 构建鉴权对象
        $auth = new Auth($accessKey, $secretKey);
        // 生成上传 Token
        return $auth->uploadToken($bucket);
    }

}



























